﻿using CaseManagerLibrary.Encrypt;
using CaseManagerLibrary.Http;
using CaseManagerLibrary.Models;
using CaseManagerLibrary.Socket;
using Newtonsoft.Json;
using PSDLib;
using PSDLib.Models;
using PSDLib.Protocols;
using PSDLib.Protocols;
using PSDManager;
using PSDManager.CreateTask;
using PSDManager.Protocols;
using PSDManager.SystemSettings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PSDManager
{
    public delegate void AddPSDEventHandler(List<PSDState> psdList);
    public delegate void AddPSDTaskEventHandler(List<DownloadTask> dtList);
    public delegate void UpdateDownloadingFilesEventHandler(List<dl_files> files);
    public delegate void UpdateBurnRuntimeEventHandler(BurnRuntime runtime);
    public class ManagerHelper
    {
        private Thread heartbeatThread;
        private Thread refreshPSDThread;
        private bool running = false;
        private bool closing = false;
        private TcpManagerAsync tcpManager;
        private string localIP;
        private IPEndPoint tcpServerEP;
        private List<PSDState> psdList;
        public List<DownloadTask> DownloadTaskList { get; private set; }
        public List<dl_server_config> DownloadServerList { get; set; }

        public TcpManagerAsync TcpManager { get { return tcpManager; } }
        public IPEndPoint ManagerEP { get; set; }

        public PSDState CurrPSD { get; set; }

        public event AddPSDEventHandler OnAddPSD;
        public event AddPSDTaskEventHandler OnAddPSDTask;
        public event UpdateDownloadingFilesEventHandler OnUpdateDownloadingFiles;
        public event UpdateBurnRuntimeEventHandler OnUpdateBurnRuntime;

        public string UUID { get; set; }
        private bool Init()
        {
            DownloadTaskList = new List<DownloadTask>();
            DownloadServerList = new List<dl_server_config>();

            UUID = DeviceUUID.GetUUID();

            psdList = new List<PSDState>();

            return StartTcpManager();
        }

        private void TcpManager_Received(string message, TcpClientState state)
        {
            try
            {
                var msg = MessageParser.Parse(message);
                var processor = ClientMessageProcessor.Parse(msg);

                if (processor != null)
                {
                    processor.Run(this);
                    System.Diagnostics.Debug.WriteLine(message);
                }
            }
            catch (Exception ex)
            { }
        }

        private bool StartTcpManager()
        {
            try
            {
                tcpServerEP = new IPEndPoint(IPAddress.Parse(AppSettings.Setting.TcpServerAddress), AppSettings.Setting.TcpServerPort);

                var listenEp = new IPEndPoint(IPAddress.Any, AppSettings.Setting.PDMListenPort);
                var sendEp = new IPEndPoint(IPAddress.Any, AppSettings.Setting.PDMSendPort);

                tcpManager = new TcpManagerAsync(listenEp);
                tcpManager.Received += TcpManager_Received;
                //tcpManager.Responsed += TcpManager_Received;
                //TcpManager.SendSuccess += TcpManager_SendSuccess;
                //tcpManager.SendFailed += TcpManager_SendFailed;
                tcpManager.Start();

                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
            //ManagerEP = NetworkHelper.GetLocalEndPoint(AppSettings.Setting.PDMPort, PSDFunction.TestConnection, tcpServerEP);

            //if (ManagerEP != null)
            //{
            //    localIP = ManagerEP.Address.ToString();

            //    ManagerEP = new IPEndPoint(IPAddress.Parse(localIP), AppSettings.Setting.PDMPort);

            //    tcpManager = new TcpManagerAsyncDUX(ep);
            //    tcpManager.Received += TcpManager_Received;
            //    tcpManager.Start();

            //    return true;
            //}
            //else
            //{
            //    return false;
            //}
        }

        private void TcpManager_SendFailed(int sent, string message, SocketState state)
        {
            if (state != null && state.SendCallback != null)
            {
                state.SendCallback(sent, message, state);
            }

            Console.WriteLine(message);
        }

        private void TcpManager_SendSuccess(int sent, string message, SocketState state)
        {
            if (state != null && state.SendCallback != null)
            {
                state.SendCallback(sent, message, state);
            }

            Console.WriteLine($"{sent} bytes sent to {state.Socket.RemoteEndPoint.ToString()}");
        }

        private void StartHeartbeat()
        {
            running = true;
            heartbeatThread = new Thread(new ThreadStart(SendHeartbeat));
            heartbeatThread.Start();
        }

        private void SendHeartbeat()
        {
            while (running)
            {
                try
                {
                    var hb = new PDMHeartbeat();
                    hb.ManagerIP = localIP;
                    hb.ManagerPort = AppSettings.Setting.PDMListenPort;
                    var msg = new PDMHeartBeatMessage() { Heartbeart = hb };

                    tcpManager.Send(tcpServerEP, msg);
                }
                catch (Exception ex)
                { }

                Thread.Sleep(20 * 1000);
            }
        }

        private void UpdateDeviceState()
        {
            while (running)
            {
                RefreshPSDList();

                Thread.Sleep(60 * 1000);
            }
        }

        public void RefreshPSDList()
        {
            try
            {
                var msg = new RequestPSDStateMessage();
                tcpManager.Send(tcpServerEP, msg);
            }
            catch (Exception ex)
            { }
        }

        /// <summary>
        /// 打开PDM管理端
        /// </summary>
        public void OpenManager()
        {
            try
            {
                if (Init())
                {
                    var msg = new OpenManagerMessage();
                    msg.Manager = new dl_manager()
                    {
                        id = UUID,
                        manager_ip = this.localIP,
                        manager_port = AppSettings.Setting.PDMListenPort
                    };
                    tcpManager.Send(tcpServerEP, msg);

                    StartHeartbeat();

                    refreshPSDThread = new Thread(new ThreadStart(UpdateDeviceState));
                    refreshPSDThread.Start();
                }
                else
                {
                    MessageBox.Show("网络初始化失败，未能连接到服务器！");
                }
            }
            catch (Exception ex)
            { }
        }

        /// <summary>
        /// 关闭PDM管理端
        /// </summary>
        public void CloseManager()
        {
            try
            {
                running = false;

                try
                {
                    heartbeatThread?.Abort();
                }
                catch { }

                try
                {
                    refreshPSDThread?.Abort();
                }
                catch { }

                if (tcpManager != null)
                {
                    closing = true;

                    var msg = new CloseManagerMessage();

                    tcpManager.Send(tcpServerEP, msg);
                    //tcpManager.Send(tcpServerEP, msg, 
                    //    (int sent, string message, SocketState state) => {
                    //        closing = false;
                    //    });

                    //while (closing)
                    //{
                    //    Thread.Sleep(500);
                    //    Application.DoEvents();
                    //}

                    tcpManager.Stop();
                }
            }
            catch (Exception ex)
            { }
        }

        /// <summary>
        /// 添加PSD设备到管理界面
        /// </summary>
        /// <param name="list"></param>
        public void AddPSD(List<PSDState> list)
        {
            psdList.Clear();
            psdList.AddRange(list);

            OnAddPSD?.Invoke(list);
        }

        public void GetPSDTask(string deviceId)
        {
            var result_task = HttpHelper.Get<HResult<List<dl_task>>>(AppSettings.Setting.API.GetDeviceTaskList + "?deviceId=" + deviceId);

            if (result_task.success)
            {
                DownloadTaskList.Clear();

                foreach (var task in result_task.data)
                {
                    var dt = new DownloadTask();
                    dt.Task = task;
                    DownloadTaskList.Add(dt);

                    var result_channel = HttpHelper.Get<HResult<List<dl_task_channel>>>(AppSettings.Setting.API.GetChannelList + "?taskId=" + task.id);
                    List<dl_task_channel> channels = null;

                    if (result_channel.success)
                    {
                        channels = result_channel.data;

                        dt.ChannelList = channels;
                    }

                    OnAddPSDTask?.Invoke(DownloadTaskList);
                }
            }
        }

        public PageResult<dl_files> GetPSDDownloadDetail(string deviceId, string taskId, string channelId, int[] state, int pageNo, int pageSize)
        {
            //var param = new Dictionary<string, string>();
            //param.Add("deviceId", deviceId);
            //param.Add("taskId", taskId);
            //param.Add("channelId", channelId);
            //param.Add("pageNo", pageNo.ToString());
            //param.Add("pageSize", pageSize.ToString());

            string query = "?pageNo=" + pageNo.ToString() + "&pageSize=" + pageSize.ToString();

            //if (!string.IsNullOrEmpty(deviceId))
            //{
            query += "&deviceId=" + deviceId;
            // }
            //if (!string.IsNullOrEmpty(taskId))
            //{
            query += "&taskId=" + taskId;
            //}
            //if (!string.IsNullOrEmpty(channelId))
            //{
            query += "&channelId=" + channelId;
            //}
            query += "&state=" + string.Join(",", state);

            var result_files = HttpHelper.Get<PageResult<dl_files>>(AppSettings.Setting.API.GetFiles + query);

            return result_files;
        }

        public PageResult<dl_task> GetTaskHistory(int pageNo, int pageSize)
        {
            string deviceId = (CurrPSD == null ? "" : CurrPSD.DeviceId);

            string query = "?deviceId=" + deviceId + "&pageNo=" + pageNo + "&pageSize=" + pageSize;

            var result_task = HttpHelper.Get<PageResult<dl_task>>(AppSettings.Setting.API.GetTaskHistory + query);

            return result_task;
        }

        public PageResult<dl_case_log> GetCaseLogList(string objectId, string logType, DateTime? startTime, DateTime? endTime, int? state, int pageNo, int pageSize)
        {
            string query = "?objectId=" + objectId + "&pageNo=" + pageNo + "&pageSize=" + pageSize;

            if (!string.IsNullOrEmpty(logType))
            {
                query += "&logType=" + logType;
            }
            if (startTime != null)
            {
                query += "&startTime=" + startTime.Value.ToString("yyyy-MM-dd");
            }
            if (endTime != null)
            {
                query += "&endTime=" + startTime.Value.ToString("yyyy-MM-dd");
            }
            if (state != null)
            {
                query += "&state=" + state.Value.ToString();
            }

            var result_log = HttpHelper.Get<PageResult<dl_case_log>>(AppSettings.Setting.API.GetCaseLogList + query);

            return result_log;
        }

        public HResult<DownloadTask> CreateDownloadTask(dl_task_start start)
        {
            var result = HttpHelper.Post<HResult<DownloadTask>>(AppSettings.Setting.API.CreateDownloadTask, JsonConvert.SerializeObject(start));

            if (result.success && result.data != null)
            {
                DownloadTaskList.Add(result.data);
            }

            return result;
        }

        public HResult CreateDownloadEntryTask(dl_entry_task_start start)
        {
            var result = HttpHelper.Post<HResult>(AppSettings.Setting.API.CreateDownloadTaskForEntry, JsonConvert.SerializeObject(start));

            return result;
        }

        public HResult CreateDownloadLeaveTask(dl_leave_task_start start)
        {
            var result = HttpHelper.Post<HResult>(AppSettings.Setting.API.CreateDownloadTaskForLeave, JsonConvert.SerializeObject(start));

            return result;
        }
        public HResult CreateDownloadTalkOutTask(dl_talk_out_task_start start)
        {
            var result = HttpHelper.Post<HResult>(AppSettings.Setting.API.CreateDownloadTaskForTalkOut, JsonConvert.SerializeObject(start));

            return result;
        }
        public HResult CreateDownloadTalkBackTask(dl_talk_out_task_start start)
        {
            var result = HttpHelper.Post<HResult>(AppSettings.Setting.API.CreateDownloadTaskForTalkBack, JsonConvert.SerializeObject(start));

            return result;
        }
        public HResult CreateDownloadTalkTask(dl_task_talk_start start)
        {
            var result = HttpHelper.Post<HResult>(AppSettings.Setting.API.CreateDownloadTaskForTalk, JsonConvert.SerializeObject(start));

            return result;
        }
        public HResult CreateDownloadChangeRoomDailyTask(dl_change_room_task_start start)
        {
            var data = new Dictionary<string, string>();
            data.Add("oldRoomNum", start.oldRoomNum);
            data.Add("newRoomNum", start.newRoomNum);
            data.Add("objectId", start.objectId);
            data.Add("changeTime", start.startTime.ToString("yyyy-MM-dd HH:mm:ss"));

            var result = HttpHelper.Post<HResult>(AppSettings.Setting.API.ChangeRoom, data);

            return result;
        }
        public HResult CreateDownloadChangeRoomRouteTask(dl_change_room_task_start start)
        {
            var result = HttpHelper.Post<HResult>(AppSettings.Setting.API.CreateDownloadTaskForChangeRoom, JsonConvert.SerializeObject(start));

            return result;
        }
        public HResult CreateDownloadRelieveTask(dl_relieve_task_start start)
        {
            var result = HttpHelper.Post<HResult>(AppSettings.Setting.API.CreateDownloadTaskForRelieve, JsonConvert.SerializeObject(start));

            return result;
        }
        public HResult CreateDownloadTaskCameraSD(dl_task_camera_sd_start start)
        {
            var result = HttpHelper.Post<HResult>(AppSettings.Setting.API.CreateDownloadTaskForCameraSDCard, JsonConvert.SerializeObject(start));

            return result;
        }

        public HResult CreateBurnTask(BurnTask task)
        {
            try
            {
                var ds = psdList.Where(t => t.DeviceId == task.BurnInfo.device_id && t.Online == true).FirstOrDefault();

                if (ds != null)
                {
                    var msg = new StartBurnDVDMessage();
                    msg.BurnTask = task;
                    msg.DeviceId = ds.DeviceId;

                    var deviceEP = new IPEndPoint(IPAddress.Parse(ds.DeviceInfo.device_ip), ds.DeviceInfo.device_port);

                    var ret = tcpManager.Send(deviceEP, msg);

                    if (ret.success)
                    {
                        ret = HttpHelper.Post<HResult>(AppSettings.Setting.API.CreateBurnTask, JsonConvert.SerializeObject(task));
                    }

                    return ret;
                }
                else
                {
                    return new HResult() { success = false, message = "设备不存在" };
                }
            }
            catch (Exception ex)
            {
                return new HResult() { success = false, message = ex.Message };
            }
        }

        //public HResult AddPSDTask(dl_task task)
        //{
        //    string json = JsonConvert.SerializeObject(task);

        //    var result = HttpHelper.Post<HResult>(AppSettings.Setting.API.AddTask, json);

        //    return result;
        //}

        //public HResult AddPSDTaskChannel(dl_task_channel channel)
        //{
        //    string json = JsonConvert.SerializeObject(channel);

        //    var result = HttpHelper.Post<HResult>(AppSettings.Setting.API.AddChannel, json);

        //    return result;
        //}

        public PSDState GetOnlinePSDState(string deviceId)
        {
            var ds = psdList.Where(t => t.DeviceId == deviceId && t.Online == true).FirstOrDefault();

            return ds;
        }

        /// <summary>
        /// 向指定PSD设备请求运行明细数据
        /// </summary>
        /// <param name="deviceId"></param>
        public void RequestPSDDetail(string deviceId)
        {
            try
            {
                var ds = psdList.Where(t => t.DeviceId == deviceId && t.Online == true).FirstOrDefault();

                if (ds != null)
                {
                    var msg = new RequestPSDDownloadingFilesMessage();
                    msg.ManagerIP = localIP;
                    msg.ManagerPort = AppSettings.Setting.PDMListenPort;

                    var deviceEP = new IPEndPoint(IPAddress.Parse(ds.DeviceInfo.device_ip), ds.DeviceInfo.device_port);

                    tcpManager.Send(deviceEP, msg);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 向指定PSD设备发送开始下载消息
        /// </summary>
        /// <param name="deviceId"></param>
        public void StartPSDDownload(string deviceId, dl_task task, List<dl_task_channel> channels)
        {
            //DownloadTask dt = new DownloadTask();
            //dt.Task = task;
            //dt.ChannelList = channels;
            var task_result = HttpHelper.Post<HResult>(AppSettings.Setting.API.StartDownloadTask, new Dictionary<string, string> { { "taskId", task.id } });

            if (task_result.success)
            {
                var ds = this.psdList.Where(t => t.DeviceId == deviceId && t.Online == true).FirstOrDefault();

                if (ds != null)
                {
                    var msg = new RefreshPSDTaskMessage();

                    var deviceEP = new IPEndPoint(IPAddress.Parse(ds.DeviceInfo.device_ip), ds.DeviceInfo.device_port);
                    tcpManager.Send(deviceEP, msg);
                }
            }
        }

        /// <summary>
        /// 向指定PSD设备发送停止下载消息
        /// </summary>
        /// <param name="deviceId"></param>
        public void StopPSDDownload(string deviceId, dl_task task, List<dl_task_channel> channels)
        {
            //DownloadTask dt = new DownloadTask();
            //dt.Task = task;
            //dt.ChannelList = channels;
            var task_result = HttpHelper.Post<HResult>(AppSettings.Setting.API.StopDownloadTask, new Dictionary<string, string> { { "taskId", task.id } });

            if (task_result.success)
            {
                var ds = this.psdList.Where(t => t.DeviceId == deviceId && t.Online == true).FirstOrDefault();

                if (ds != null)
                {
                    var msg = new RefreshPSDTaskMessage();

                    var deviceEP = new IPEndPoint(IPAddress.Parse(ds.DeviceInfo.device_ip), ds.DeviceInfo.device_port);
                    tcpManager.Send(deviceEP, msg);
                }
            }
        }

        public void IgnoreFail(string deviceId, List<string> ignoreList)
        {
            var ds = this.psdList.Where(t => t.DeviceId == deviceId && t.Online == true).FirstOrDefault();

            if (ds != null)
            {
                var msg = new IgnoreDownloadFailMessage();
                msg.IgnoreList.AddRange(ignoreList);

                var deviceEP = new IPEndPoint(IPAddress.Parse(ds.DeviceInfo.device_ip), ds.DeviceInfo.device_port);
                tcpManager.Send(deviceEP, msg);
            }
        }


        public void ReDownloadFile(string deviceId, string fileId)
        {
            Dictionary<string, string> data = new Dictionary<string, string>();
            data.Add("fileId", fileId);

            var result = HttpHelper.Post<HResult>(AppSettings.Setting.API.ReDownloadFile, data);

            if (result.success)
            {
                var ds = this.psdList.Where(t => t.DeviceId == deviceId && t.Online == true).FirstOrDefault();

                if (ds != null)
                {
                    var msg = new RefreshPSDDownlodingFilesMessage();

                    var deviceEP = new IPEndPoint(IPAddress.Parse(ds.DeviceInfo.device_ip), ds.DeviceInfo.device_port);
                    tcpManager.Send(deviceEP, msg);
                }
            }
        }

        public void FinishPSDDownload(string deviceId, dl_task task, List<dl_task_channel> channels)
        {
            //DownloadTask dt = new DownloadTask();
            //dt.Task = task;
            //dt.ChannelList = channels;
            var task_result = HttpHelper.Post<HResult>(AppSettings.Setting.API.FinishDownloadTask, new Dictionary<string, string> { { "taskId", task.id } });

            if (task_result.success)
            {
                var ds = this.psdList.Where(t => t.DeviceId == deviceId && t.Online == true).FirstOrDefault();

                if (ds != null)
                {
                    var msg = new RefreshPSDTaskMessage();

                    var deviceEP = new IPEndPoint(IPAddress.Parse(ds.DeviceInfo.device_ip), ds.DeviceInfo.device_port);
                    tcpManager.Send(deviceEP, msg);
                }
            }
        }

        public void DeletePSDDownload(string deviceId, dl_task task, List<dl_task_channel> channels)
        {
            //DownloadTask dt = new DownloadTask();
            //dt.Task = task;
            //dt.ChannelList = channels;
            var task_result = HttpHelper.Post<HResult>(AppSettings.Setting.API.DeleteDownloadTask, new Dictionary<string, string> { { "taskId", task.id } });

            if (task_result.success)
            {
                var ds = this.psdList.Where(t => t.DeviceId == deviceId && t.Online == true).FirstOrDefault();

                if (ds != null)
                {
                    var msg = new RefreshPSDTaskMessage();

                    var deviceEP = new IPEndPoint(IPAddress.Parse(ds.DeviceInfo.device_ip), ds.DeviceInfo.device_port);
                    tcpManager.Send(deviceEP, msg);
                }
            }
        }



        public HResult SetTaskTime(string taskId, DateTime startTime, DateTime? endTime)
        {
            Dictionary<string, string> data = new Dictionary<string, string>();
            data.Add("taskId", taskId);
            data.Add("startTime", startTime.ToString("yyyy-MM-dd HH:mm:ss"));
            data.Add("endTime", (endTime == null ? "" : endTime.Value.ToString("yyyy-MM-dd HH:mm:ss")));

            var ret = HttpHelper.Post<HResult>(AppSettings.Setting.API.SetTaskTime, data);

            return ret;
        }

        public void SetPSDName(string deviceId, string deviceName)
        {
            var msg = new SetPSDNameMessage();
            msg.DeviceId = deviceId;
            msg.DeviceName = deviceName;

            tcpManager.Send(tcpServerEP, msg);
        }

        public void SetPSDMaxDownloadProcess(string deviceId, int process)
        {
            var msg = new SetPSDMaxDownloadProcessMessage();
            msg.DeviceId = deviceId;
            msg.Process = process;

            tcpManager.Send(tcpServerEP, msg);
        }

        public void ResponsePSDDownloadingFiles(List<dl_files> files)
        {
            OnUpdateDownloadingFiles?.Invoke(files);
        }

        public void RestartPSDDownloadService(string deviceId)
        {
            var ds = this.psdList.Where(t => t.DeviceId == deviceId && t.Online == true).FirstOrDefault();

            if (ds != null)
            {
                var msg = new RestartPSDDownloadServiceMessage();

                var deviceEP = new IPEndPoint(IPAddress.Parse(ds.DeviceInfo.device_ip), ds.DeviceInfo.device_port);
                tcpManager.Send(deviceEP, msg);
            }
        }

        public void RebootPSD(string deviceId)
        {
            var ds = this.psdList.Where(t => t.DeviceId == deviceId && t.Online == true).FirstOrDefault();

            if (ds != null)
            {
                var msg = new RebootPSDDeviceMessage();

                var deviceEP = new IPEndPoint(IPAddress.Parse(ds.DeviceInfo.device_ip), ds.DeviceInfo.device_port);
                tcpManager.Send(deviceEP, msg);
            }
        }

        public void ShutdownPSD(string deviceId)
        {
            var ds = this.psdList.Where(t => t.DeviceId == deviceId && t.Online == true).FirstOrDefault();

            if (ds != null)
            {
                var msg = new ShutDownPSDDeviceMessage();

                var deviceEP = new IPEndPoint(IPAddress.Parse(ds.DeviceInfo.device_ip), ds.DeviceInfo.device_port);
                tcpManager.Send(deviceEP, msg);
            }
        }

        //public void UpdatePSDServerSetting(string apiServerAddress, string tcpServerAddress, int tcpServerPort)
        //{
        //    var dsList = this.psdList.Where(t => t.Online == true).ToList();

        //    foreach (var ds in dsList)
        //    {
        //        var msg = new UpdatePSDServerSettingMessage();


        //        var deviceEP = new IPEndPoint(IPAddress.Parse(ds.DeviceInfo.device_ip), ds.DeviceInfo.device_port);
        //        tcpManager.Send(deviceEP, msg);
        //    }
        //}

        public void UpdatePSDSetting(string deviceId)
        {
            var ds = this.psdList.Where(t => t.DeviceId == deviceId && t.Online == true).FirstOrDefault();

            if (ds != null)
            {
                var msg = new UpdatePSDSettingMessage();
                msg.ApiServerAddress = AppSettings.Setting.ApiServerAddress;
                msg.TcpServerAddress = AppSettings.Setting.TcpServerAddress;
                msg.TcpServerPort = AppSettings.Setting.TcpServerPort;

                var deviceEP = new IPEndPoint(IPAddress.Parse(ds.DeviceInfo.device_ip), ds.DeviceInfo.device_port);
                tcpManager.Send(deviceEP, msg);
            }
        }


        public void BurnTaskDenied(BurnJobDeniedMessage msg)
        {

        }

        public void ResponseBurnRuntime(BurnRuntime runtime)
        {
            OnUpdateBurnRuntime?.Invoke(runtime);
        }

        public void ResumeBurn(string deviceId)
        {
            var ds = this.psdList.Where(t => t.DeviceId == deviceId && t.Online == true).FirstOrDefault();

            if (ds != null)
            {
                var msg = new ResumeBurnMessage();

                var deviceEP = new IPEndPoint(IPAddress.Parse(ds.DeviceInfo.device_ip), ds.DeviceInfo.device_port);
                tcpManager.Send(deviceEP, msg);
            }
        }

        public HResult UploadVersionFile(dl_psd_version_file_vo file)
        {
            var msg = new UploadVersionFileMessage();
            msg.FileName = file.file_name;
            msg.FilePath = file.file_path;
            msg.FileSign = file.sign;
            msg.FileData = FileValidHelper.GetFileData(file.local_path);

            var result = tcpManager.Send(tcpServerEP, msg);

            return result;

        }

        public void DownloadLogImmediate(string deviceId)
        {
            var ds = this.GetOnlinePSDState(deviceId);

            if (ds != null)
            {
                var msg = new DownloadLogMessage();

                var deviceEP = new IPEndPoint(IPAddress.Parse(ds.DeviceInfo.device_ip), ds.DeviceInfo.device_port);

                this.TcpManager.Send(deviceEP, msg);
            }
        }

    }
}
